package handler

import (
	"github.com/gin-gonic/gin"
	"pen-manager/model"
	"pen-manager/pkg"
	"strconv"
)

func Article(c *gin.Context) {
	title := c.PostForm("title")
	content := c.PostForm("content")
	img := c.PostForm("img")
	if title == "" || content == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "不能为空",
		})
		return
	}
	data := &model.Article{
		Title:   title,
		Content: content,
		Img:     img,
	}
	err := model.DB.Create(&data).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "添加失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})
}

func DelArticle(c *gin.Context) {
	id := c.Query("id")
	var article model.Article
	err := model.DB.Where("id=?", id).Delete(&article).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "删除失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "删除成功",
	})
}

func DetailArticle(c *gin.Context) {
	id := c.Query("id")
	var article model.Article
	err := model.DB.Where("id=?", id).First(&article).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "获取详情失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "获取详情成功",
		"data": article,
	})
}

func ListArticle(c *gin.Context) {
	//uid, _ := c.Get("uid")
	//c.JSON(200, gin.H{
	//	"code": 200,
	//	"msg":  "登陆成功",
	//	"uid":  uid,
	//})
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	size, _ := strconv.Atoi(c.DefaultQuery("size", "3"))
	offset := (page - 1) * size
	var count int64
	err := model.DB.Model(&model.Article{}).Count(&count).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "获取条数失败",
		})
		return
	}
	var article []model.Article
	err = model.DB.Offset(offset).Limit(size).Find(&article).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "获取数据失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "获取数据成功",
		"data": gin.H{
			"article": article,
			"count":   count,
		},
	})

}

func Login(c *gin.Context) {
	uid := c.Query("uid")
	token, _ := pkg.TokenHandler(uid)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "success",
		"data": token,
	})
}
